package com.leaf.spring.y201906.day18.springmvc;

import java.io.File;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * 此处试验用了tomcat8， tomcat9有问题，待查
 * 
 * @Title:
 * @Description:
 * @Author: leaf
 * @Since:2019年6月18日
 * @Version:1.1.0
 */
public class SpringApplicationLeaf {

	public static void run() throws LifecycleException {

		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(AppConfig.class);
		context.refresh();

		// 获取操作系统缓存的临时目录
		File base = new File(System.getProperty("java.io.tmpdir"));

//		URL resource = ClassLoader.getSystemClassLoader().getResource("");
//
//		String sbase = resource.getFile();

		Tomcat tomcat = new Tomcat();
		tomcat.setPort(8888);

//		Context rootContext = tomcat.addContext("/", sbase);
		Context rootContext = tomcat.addContext("/", base.getAbsolutePath());

		DispatcherServlet dispatcherServlet = new DispatcherServlet(context);

		// 初始化tomcat和请求映射
		Tomcat.addServlet(rootContext, "leaf", dispatcherServlet).setLoadOnStartup(0);

		rootContext.addServletMappingDecoded("/", "leaf");

		tomcat.start();
		tomcat.getServer().await();

		/**
		 * 初始化 org.springframework.web.servlet.HttpServletBean.init()
		 * org.springframework.web.servlet.FrameworkServlet.initServletBean()
		 * org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext()
		 * org.springframework.web.servlet.DispatcherServlet.onRefresh(ApplicationContext)
		 * org.springframework.web.servlet.DispatcherServlet.initStrategies(ApplicationContext)
		 * 
		 * 请求处理 HttpServlet.service()
		 * org.springframework.web.servlet.FrameworkServlet.doGet/doPost()
		 * org.springframework.web.servlet.FrameworkServlet.processRequest()
		 * DispatcherServlet.doService() DispatcherServlet.doDispatch()
		 * checkMultipart(request) -> 文件上传
		 * <p>
		 * getHandler(request) -> 获取HandlerExecutionChain
		 * <p>
		 * getHandlerAdapter() -> 获取HandlerAdapter
		 * <p>
		 * HandlerAdapter.handle()
		 * 
		 * RequestMappingHandlerMapping的作用
		 * 1. 通过request查找对应的HandlerMethod，即当前request具体是由Controller中的哪个方法进行处理；
		 * 2. 查找当前系统中的Interceptor，将其与HandlerMethod封装为一个HandlerExecutionChain。
		 * 
		 */

	}

}
